﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Threading;
using DoxygenBrowser.Common.Model;
using DoxygenBrowser.Common.Parser;
using System.IO;
using DoxygenBrowserAddin.Data;

namespace DoxygenBrowserAddin.Controller
{
  public class TokenDictionaryLoader
  {
		public event ProgressChangedEventHandler ProgressChangedEvent; 

    private string _strTokenFilePath;

    private TokenDictionary _tokenDictionary;
    public TokenDictionary TokenDictionary
    {
      get
      {
        return _tokenDictionary;
      }
    }

    private void WorkerThreadFunction()
    {
      // parse or load the token dictionary

    }

    public TokenDictionaryLoader(string strTokenFilePath)
    {
      _strTokenFilePath = strTokenFilePath;
      _tokenDictionary = new TokenDictionary();
    }

    public bool IsLoading
    {
      get { return false; }
    }

    public void Process()
    {
			using (StreamReader txtReader = new StreamReader(_strTokenFilePath, Encoding.ASCII))
			{
				DocsetParser parser = new DocsetParser();
      parser.TokenAddedEvent +=new EventHandler<TokenAddedEventArgs>(this.HandleTokenAdded);
				parser.ProgressChangedEvent += new ProgressChangedEventHandler(parser_ProgressChangedEvent);
				parser.Parse(txtReader.BaseStream);
				parser.ProgressChangedEvent -= parser_ProgressChangedEvent;
				txtReader.Close();
			}
    	OnCompletedWork();
    }

		void parser_ProgressChangedEvent(object sender, ProgressChangedEventArgs e)
		{
			if (ProgressChangedEvent != null)
			{
				ProgressChangedEvent(this, new ProgressChangedEventArgs(e.ProgressPercentage, null));
			}
    }

    public void Stop()
    {
      
    }

    public void HandleTokenAdded(object sender, TokenAddedEventArgs e)
    {
    	string key = e.TokenIdentifier.FullName;
    	key = normalizeIdentifier(key);

      _tokenDictionary.AddTokenEntry(key, e.FileLocation);
    }

		private string normalizeIdentifier(string key)
		{
			string normalizedKey = key;
			normalizedKey = normalizedKey.Replace("&lt;", "<");
			normalizedKey = normalizedKey.Replace("&gt;", "<");
			normalizedKey = normalizedKey.Replace(" ", "");
			return normalizedKey;
    }
      

    public void OnUpdateWorkStatus()
    {
      
    }

    public void OnCompletedWork()
    {
      
    }
  }
}
